﻿using UnityEngine;
using System.Collections;
using LitJson;
//东边日出西边雨，道是无情却有情

public class SpawnPoint : MonoBehaviour {
	//level object
	public LevelObject levelObject;
	public EnemyConfig enemyConfig;

	//update screen position (-1,1)~
	public Vector2 screenAnchor;
	public float xOffset;
	public float yOffset;
	public int id = 0;

	private double elapsedTime = 0;
	
	// Use this for initialization
	void Start () {

	}
	
	// Update is called once per frame
	void Update () {

		elapsedTime += Time.deltaTime;

		//update spawn point position
		updatePosition ();

		//update spawn
		updateSpawn ();
	}

	void updatePosition(){
		Vector3 newPosition = transform.position;
		Camera camera = Camera.main;
		newPosition.y = camera.orthographicSize * screenAnchor.y + yOffset + camera.transform.position.y;
		newPosition.x = camera.aspect * camera.orthographicSize * screenAnchor.x + xOffset + camera.transform.position.x;
		transform.position = newPosition;
	}

	void updateSpawn(){
		LevelInfo levelInfo = levelObject.levelInfo;
		double totalWaveTime = 0;
		int nextWaveIndex = -1;
		for(int i = 0; i < levelInfo.waves_list.Count; i++ ){
			EnemyWave enemyWave = levelInfo.waves_list[i];
			if(enemyWave.isAllFire ||
			   isAllEnemySpawned(enemyWave)){
				totalWaveTime += enemyWave.delay;
			}else{
				nextWaveIndex = i;
				break;
			}
		}

		//check to see if create a wave
		if(nextWaveIndex != -1){
			EnemyWave enemyWave = levelInfo.waves_list[nextWaveIndex];
			totalWaveTime += enemyWave.delay;
			if(elapsedTime > totalWaveTime){
				//create enemy wave
				createEnemyWave(enemyWave);
			}
		}
	}

	void createEnemyWave(EnemyWave enemyWave){
		for(int i=0; i<enemyWave.enemy_list.Count; i++){
			EnemyInfo enemyInfo = enemyWave.enemy_list[i];
			if(enemyInfo.spawn == id &&
			   !enemyInfo.isFire){
				enemyInfo.isFire = true;
				StartCoroutine(createEnemy(enemyInfo));
			}
		}
	}

	bool isAllEnemySpawned(EnemyWave enemyWave){
		bool bRet = true;
		for(int i=0; i<enemyWave.enemy_list.Count; i++){
			EnemyInfo enemyInfo = enemyWave.enemy_list[i];
			if(!enemyInfo.isFire){
				bRet = false;
				break;
			}
		}
		if(bRet){
			enemyWave.isAllFire = true;
		}

		return bRet;
	}

	IEnumerator createEnemy(EnemyInfo enemyInfo){
		yield return new WaitForSeconds	((float)enemyInfo.delay);

		//create enemy
		EnemyMsg enemyMsg = enemyConfig.getEnemyMsgById (enemyInfo.id);
		GameObject.Instantiate(Resources.Load ("Prefabs/" + enemyMsg.prefab),transform.position,transform.rotation);
	}
}




